package com.bookcloud.java21.aitools;

import java.awt.*;
import java.util.List;
import javax.swing.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

/** Sign-in Statistical Chart UI Panel 签到统计图表界面 */
public class SignStatisticalChartUI extends JPanel {

  private ChartPanel chartPanel;
  private JFreeChart chart;

  // Color constants
  private static final Color SIGNED_BAR_COLOR =
      new Color(70, 130, 180); // 钢蓝色 - 用于签到次数柱状图
  private static final Color UNSIGNED_BAR_COLOR =
      new Color(220, 20, 60); // 深红色 - 用于未签到次数柱状图
  private static final Color RATE_LINE_COLOR =
      new Color(255, 165, 0); // 橙色 - 用于签到率折线图

  public SignStatisticalChartUI() {
    initializeComponents();
    layoutComponents();
    loadChartData();
  }

  /** Initialize all UI components 初始化所有UI组件 */
  private void initializeComponents() {
    // Create chart with combined bar and line chart
    createChart();

    // Create chart panel
    chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new Dimension(800, 500));
    chartPanel.setMouseWheelEnabled(true);
    chartPanel.setMouseZoomable(true);
  }

  /** Create the combined bar and line chart 创建组合柱状图和折线图 */
  private void createChart() {
    // Create dataset for bars (attendance and absence counts)
    CategoryDataset barDataset = createBarDataset();

    // Create the bar chart
    chart =
        ChartFactory.createBarChart(
            "学生统计图表", // Chart title
            "学生", // X-axis label
            "人数", // Y-axis label
            barDataset, // Dataset
            PlotOrientation.VERTICAL,
            true, // Show legend
            true, // Show tooltips
            false // Show URLs
            );

    // Customize the chart
    customizeChart();

    // Add line chart for attendance rate
    addAttendanceRateLine();
  }

  /** Create bar dataset for attendance and absence counts 创建签到和缺席人数的柱状图数据集 */
  private CategoryDataset createBarDataset() {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    // Get chart data from DataUtil
    List<StudentChartData> chartDataList = DataUtil.getStudentChartData();

    for (StudentChartData data : chartDataList) {
      dataset.addValue(data.getSignedDays(), "签到次数", data.getName());
      dataset.addValue(data.getAbsentDays(), "未签到次数", data.getName());
    }

    return dataset;
  }

  /** Customize chart appearance 自定义图表外观 */
  private void customizeChart() {
    CategoryPlot plot = chart.getCategoryPlot();

    // Set background colors
    chart.setBackgroundPaint(Color.WHITE);
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // Customize bar renderer
    BarRenderer barRenderer = (BarRenderer) plot.getRenderer();
    barRenderer.setSeriesPaint(0, SIGNED_BAR_COLOR); // Series 0: 签到次数 (signed attendance bars)
    barRenderer.setSeriesPaint(1, UNSIGNED_BAR_COLOR); // Series 1: 未签到次数 (unsigned attendance bars)
    // barRenderer.setBarPainting3D(false);

    // Customize axes
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 10));
    domainAxis.setCategoryLabelPositions(org.jfree.chart.axis.CategoryLabelPositions.UP_45);

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // Set chart title font
    chart.getTitle().setFont(new Font("微软雅黑", Font.BOLD, 16));
    
    // Set legend font
    chart.getLegend().setItemFont(new Font("微软雅黑", Font.PLAIN, 12));
  }

  /** Add attendance rate line chart overlay 添加签到率折线图覆盖层 */
  private void addAttendanceRateLine() {
    CategoryPlot plot = chart.getCategoryPlot();

    // Create dataset for attendance rate line
    DefaultCategoryDataset lineDataset = new DefaultCategoryDataset();

    List<StudentChartData> chartDataList = DataUtil.getStudentChartData();
    for (StudentChartData data : chartDataList) {
      lineDataset.addValue(data.getAttendanceRate(), "签到率", data.getName());
    }

    // Add second axis for attendance rate (percentage)
    NumberAxis secondAxis = new NumberAxis("签到率(%)");
    secondAxis.setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
    secondAxis.setRange(0, 100);
    plot.setRangeAxis(1, secondAxis);
    plot.setDataset(1, lineDataset);
    plot.mapDatasetToRangeAxis(1, 1);

    // Create line renderer for attendance rate
    LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer();
    lineRenderer.setSeriesPaint(0, RATE_LINE_COLOR); // 橙色折线显示签到率
    lineRenderer.setSeriesStroke(0, new BasicStroke(2.0f));
    lineRenderer.setSeriesShapesVisible(0, true);
    lineRenderer.setSeriesShape(0, new java.awt.geom.Ellipse2D.Double(-3, -3, 6, 6));

    plot.setRenderer(1, lineRenderer);
  }

  /** Layout all components 布局所有组件 */
  private void layoutComponents() {
    setLayout(new BorderLayout());
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    setBackground(Color.WHITE);

    // Add chart panel to center
    add(chartPanel, BorderLayout.CENTER);
  }

  /** Load chart data and refresh display 加载图表数据并刷新显示 */
  private void loadChartData() {
    // Chart data is loaded during chart creation
    // This method can be used for future data refresh functionality
  }

  /** Refresh chart data and update display 刷新图表数据并更新显示 */
  public void refreshData() {
    // Recreate chart with updated data
    createChart();
    chartPanel.setChart(chart);
    chartPanel.repaint();
  }

  /** Inner class to represent student chart data 学生图表数据内部类 */
  public static class StudentChartData {
    private String name;
    private int signedDays;
    private int absentDays;
    private double attendanceRate;

    public StudentChartData(String name, int signedDays, int absentDays) {
      this.name = name;
      this.signedDays = signedDays;
      this.absentDays = absentDays;
      this.attendanceRate = (double) signedDays / (signedDays + absentDays) * 100;
    }

    // Getters
    public String getName() {
      return name;
    }

    public int getSignedDays() {
      return signedDays;
    }

    public int getAbsentDays() {
      return absentDays;
    }

    public double getAttendanceRate() {
      return attendanceRate;
    }
  }
}
